using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media.Imaging;

namespace MediaOwl.Common.Converters
{
    public class ImageSourceConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return null;

            Uri uri = value.ToString().StartsWith("http") 
                ? new Uri(value.ToString(), UriKind.Absolute) 
                : new Uri(value.ToString(), UriKind.Relative);
            
            return new BitmapImage(uri);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is BitmapImage)
            {
                return ((BitmapImage)value).UriSource.ToString();
            }
            return null;
        }
    }
}